require 'net/http'
class WebsitearticlesController < ApplicationController
before_filter :authorize
    layout "websitearticles4"

      active_scaffold :article do |config|
  config.label = "Articles"
#  config.action_links.add 'export_csv', :label => 'Export to Excel', :page => true 
  config.show.link.label = "Show Detail"  
  config.show.link.type = :record
  config.show.link.inline = true
  config.show.link.position = :after 
  

 	  
	  config.columns[:websitesinf].form_ui = :select 
    config.columns[:websitesinf].label = 'Websites Copy To' 	  
    config.columns[:user_published_by].label = 'Alias' 	  
	  config.columns[:tag].form_ui = :select 
	  config.columns[:categoryt].form_ui = :select 	     
	  config.columns[:category].form_ui = :select  
	  
    config.columns[:published].label = 'P'	  
    config.columns[:category].label = 'Category 1' 	
    config.columns[:categoryt].label = 'Category 2' 	    	  
	  
    config.columns[:synopsis].form_ui = :textarea
    config.columns[:synopsis].options = {:rows => 60, :cols => 100}

# config.columns[:original_link].options = {:size => 80}
    config.columns[:body].form_ui = :textarea
    config.columns[:body].options = {:rows => 60, :cols => 100}
    
#    config.columns[:published].form_ui = :checkbox    
# 	  config.columns[:published].inplace_edit = true
	  config.columns = [:websitesinf,:title,:synopsis,:body,:category,:categoryt,:body,:tag,:created_by,:created_at,:published,:published_at,:last_accessed_at,:imageurl,:original_link,:last_accessed_user,:last_updated_at,:last_updated_user,:user_published_by]
    config.list.columns.exclude :imageurl,:body,:original_link,:websitesinf,:last_accessed_user,:last_updated_at,:last_updated_user,:last_accessed_at,:created_by,:created_at,:published_at,:category,:categoryt,:tag

#    config.action_links.add 'mytest', :label => 'Websites', :type => :record, :page => true

		config.action_links.add 'mytest3', :label => 'Copy', :type => :record, :page => true
		config.action_links.add 'mytest1', :label => 'Photos', :type => :record, :page => true
		config.action_links.add 'mytest2', :label => 'New Tag', :type => :record, :page => true

    config.create.columns.exclude(:synopsis,:body,:created_at,:created_by,:published_at,:last_accessed_at,:last_accessed_user,:last_updated_at,:last_updated_user)  
    config.create.columns.add_subgroup "Detail Information"  do |group|       
       	group.add(:synopsis,:body) 
       	end     
       	
    config.update.columns.exclude(:websitesinf,:synopsis,:body,:created_by,:created_at,:published_at,:last_accessed_at,:last_accessed_user,:last_updated_at,:last_updated_user)  
    config.update.columns.add_subgroup "Detail Information"  do |group|       
    	group.add(:synopsis,:body)  
    	end  

    config.show.columns.exclude(:websitesinf,:synopsis,:title,:created_by,:created_at,:published,:published_at,:last_accessed_at,:last_accessed_user,:last_updated_at,:last_updated_user,:user_published_by)       	
  config.show.label = "Show Detail"

  end
  
  def destroy
    @articlet = Article.find(params[:id])
    super

    @wsurln = Websitesinf.find(@articlet.websitesinf_id).url1	    
    s_wsaddr = ""    
      case @wsurln.downcase
        when "www.deathtoglamour.com" : 
              s_wsaddr = "http://84.234.17.41:3009/"+"backend/api"
                                             
        else 
              s_wsaddr = ""
        
      end     
    
    if s_wsaddr != ""
           blog = ActionWebService::Client::Soap.new(ArticleApi, s_wsaddr)

 		  		 blog.del_article(@articlet.title)  
 		end

  end
  
  def show
    super

    @article = Article.find(params[:id])
    @article.last_accessed_user = User.find(session[:user_id]).name
    @article.last_accessed_at = Time.now
    @article.save

  end
  
  def submpostartic
		  @articobj = Article.find(params[:id])
		  @articobj.published = true
		  @articobj.save
		  
    begin     
    	 @categn = Category.find(@articobj.category_id)
      rescue ActiveRecord::RecordNotFound
        @categn = nil
    end		  

		  
		  if @categn.nil?
		  		   @categname = ""

		  else
		   @categname = @categn.name
		  end
		  
    begin     
    	 @categnt = Categoryt.find(@articobj.categoryt_id)
      rescue ActiveRecord::RecordNotFound
        @categnt = nil
    end		  

		  
		  if @categnt.nil?
		  		   @categnamet = ""

		  else
		   @categnamet = @categnt.name
		  end		  
		  
		  begin
		   @photouobj = Photo.find(:first,:conditions=>["photos.ualia_id = ?",(Ualia.find_by_name(@articobj.user_published_by)).id])		  	     
      rescue ActiveRecord::RecordNotFound
        @photouobj = nil
      end		
      
      if @photouobj.nil?
		   @photouname = ""
		  else
		   @photouname = "http://www.click2edit.com"+@photouobj.public_filename
		  end
		  
		  @imageurlobj = Imageurl.find(:first,:conditions=>["imageurls.article_id = ?",params[:id]])		  
		  
		  if @imageurlobj
		   @imageurlname = @imageurlobj.simgurl
		  else
		   @imageurlname = ""
		  end
		  
		  begin
		   @ualiaobj = Ualia.find_by_name(@articobj.user_published_by)
		  rescue ActiveRecord::RecordNotFound
        @ualiaobj = nil
      end	
      
		  if @ualiaobj.nil?
		   @uprofiled = ""
		   @uemail = ""
		  else
		   @uprofiled = @ualiaobj.profile
		   @uemail = @ualiaobj.email_addr
		  end      
		  
		  begin
		   @tagobj = Tag.find(@articobj.tag_id) 
		  rescue ActiveRecord::RecordNotFound
		    @tagobj = nil
		  end
		  
		  if @tagobj.nil?
		   @tagname = ""
		  else
		   @tagname = @tagobj.name
		  end
		  
    @wsurln = Websitesinf.find(@articobj.websitesinf_id).url1		  
    s_wsaddr = ""    
      case @wsurln.downcase
        when "www.deathtoglamour.com" : 
              s_wsaddr = "http://84.234.17.41:3009/"+"backend/api"
                                             
        else 
              s_wsaddr = ""
        
      end 		  
      
    if s_wsaddr != ""      
     blog = ActionWebService::Client::Soap.new(ArticleApi, s_wsaddr)
 		 blog.ins_article(@articobj.title,@articobj.synopsis,@articobj.body,@articobj.user_published_by,@imageurlname,@uemail,@categname,@photouname,@uprofiled,@categnamet,@tagname)  
    end
  end
  


	def after_create_save(record); 
		  record.websitesinf_id = params[:id]
	    record.save
	    
	    if   params[:record][:websitesinf]
         params[:record][:websitesinf][':id'].each do |websid|
				   @newcopy = Article.new(:title=>record.title,:synopsis=>record.synopsis,:body=>record.body,:websitesinf_id=>websid.to_i)
							    
				   @newcopy.save

  	     end

      end
        imagefn = ""
	       image = record.imageurl
			   url = URI.parse(image) 	
				 Net::HTTP.start(url.host, url.port) {|http|
    	  resp = http.get(image)
    	  imgext =""
    	  testfilen =""
        testfilen = image[image.rindex('/')+1,image.length-image.rindex('/')-1]
        
       if  (testfilen!="")&&(testfilen.rindex('.')!=nil)
        imgext= testfilen[testfilen.rindex('.')+1,testfilen.length-testfilen.rindex('.')-1]
       end
       
	      if ((imgext=='png')||(imgext=='jpg')||(imgext=='gif'))
	        FileUtils.mkdir_p Dir.pwd+"/public/articlesimages/"+(record.id).to_s unless File.exists?(Dir.pwd+"/public/articlesimages/"+(record.id).to_s)&& File.directory?(Dir.pwd+"/public/articlesimages/"+(record.id).to_s)
	        	        imagefn = Date.today.to_s.split('-').join('')+Time.now.to_i.to_s+"_"+rand(100).to_s+"."+imgext
	    	  File.open(Dir.pwd+"/public/articlesimages/"+(record.id).to_s+"/"+imagefn, "wb")    	   { |file|    file.write(resp.body)   }
	    	end
   
		  }
		  image = "http://www.click2edit.com/articlesimages/"+(record.id).to_s+"/"+imagefn
    	@imageurl = Imageurl.new
      @imageurl.article_id = record.id
      @imageurl.simgurl = image
    	record.imageurls<< @imageurl	
#    @websitesinf = Websitesinf.find(params[:websiteid])

#    unless @websitesinf.has_article?(record.title)
#      @websitesinf.articles << record
#    end

	end
	
	def before_update_save(record); 
		  @articobj = Article.find(record.id)

	if @articobj.published
    @wsurln = Websitesinf.find(@articobj.websitesinf_id).url1			  
    s_wsaddr = ""    
      case @wsurln.downcase
        when "www.deathtoglamour.com" : 
              s_wsaddr = "http://84.234.17.41:3009/"+"backend/api"
                                             
        else 
              s_wsaddr = ""
        
      end 
      
    begin     
    	 @categn = Category.find(params[:record][:category])
      rescue ActiveRecord::RecordNotFound
        @categn = nil
    end		  

		  
		  if @categn.nil?
		  		   @categname = ""

		  else
		   @categname = @categn.name
		  end		   
		  
    begin     
    	 @categnt = Categoryt.find(params[:record][:categoryt])
      rescue ActiveRecord::RecordNotFound
        @categnt = nil
    end		  

		  
		  if @categnt.nil?
		  		   @categnamet = ""

		  else
		   @categnamet = @categnt.name
		  end		  
		  
		  begin
		   @tagobj = Tag.find(params[:record][:tag][':id']) 
		  rescue ActiveRecord::RecordNotFound
		    @tagobj = nil
		  end
		  
		  if @tagobj.nil?
		   @tagname = ""
		  else
		   @tagname = @tagobj.name
		  end		  
		  
    if s_wsaddr != ""          
     blog = ActionWebService::Client::Soap.new(ArticleApi, s_wsaddr)
 		 blog.upd_article(@articobj.title,params[:record][:title],params[:record][:synopsis],params[:record][:body]	,params[:record][:user_published_by],@categname,@categnamet,@tagname,params[:record][:imageurl])  	
    end
    
   end
		  begin
		   @imgurlobj = Imageurl.find_by_simgurl_and_article_id(params[:record][:imageurl],record.id)
      rescue ActiveRecord::RecordNotFound
        @imgurlobj = nil
      end	
      
      if (@articobj.imageurl != params[:record][:imageurl])&&(@imgurlobj.nil?)

	        imagefn = ""
		       image = record.imageurl
				   url = URI.parse(image) 	
					 Net::HTTP.start(url.host, url.port) {|http|
	    	  resp = http.get(image)
	    	  imgext =""
	    	  testfilen =""
	        testfilen = image[image.rindex('/')+1,image.length-image.rindex('/')-1]
	        
	       if  (testfilen!="")&&(testfilen.rindex('.')!=nil)
	        imgext= testfilen[testfilen.rindex('.')+1,testfilen.length-testfilen.rindex('.')-1]
	       end
	       
		      if ((imgext=='png')||(imgext=='jpg')||(imgext=='gif'))
		        FileUtils.mkdir_p Dir.pwd+"/public/articlesimages/"+(record.id).to_s unless File.exists?(Dir.pwd+"/public/articlesimages/"+(record.id).to_s)&& File.directory?(Dir.pwd+"/public/articlesimages/"+(record.id).to_s)
		        	        imagefn = Date.today.to_s.split('-').join('')+Time.now.to_i.to_s+"_"+rand(100).to_s+"."+imgext
		    	  File.open(Dir.pwd+"/public/articlesimages/"+(record.id).to_s+"/"+imagefn, "wb")    	   { |file|    file.write(resp.body)   }
		    	end
	   
			  }
			  image = "http://www.click2edit.com/articlesimages/"+(record.id).to_s+"/"+imagefn
	    	@imageurl = Imageurl.new
	      @imageurl.article_id = record.id
	      @imageurl.simgurl = image
	    	record.imageurls<< @imageurl	
  
	  end
	end
	
	def after_update_save(record); 
	

#    @websitesinf = Websitesinf.find(params[:websiteid])

#    unless @websitesinf.has_article?(record.title)
#      @websitesinf.articles << record
#    end

	end

  def update

    super
   @mytest = params[:record][:user_published_by]
    @article = Article.find(params[:id])
     @article.tag_id = params[:record][:tag][':id']    
     @article.user_published_by = @mytest     
    @article.last_updated_user = User.find(session[:user_id]).name
    @article.last_updated_at = Time.now
    @article.save

  end 
   def conditions_for_collection
#   ['articles.id in (select article_id from articles_websitesinfs where websitesinf_id = ?)',params[:websiteid] ]
   ['articles.websitesinf_id = ?',params[:id] ]
  end
  
  def do_edit
	  super
	  @opjud = "edit"
	
  end 
  
  def do_new
	  super
	  @opjud = "new"
  end 
  
  def mytest
  @all_websitesinfs = Websitesinf.find(:all)
    @article = Article.find(params[:id])
  end
  
    def mytest1
   redirect_to article_photos_path(:article_id => params[:id])
  end
  
      def mytest2
   redirect_to :controller =>'article_tags',:action=>'index',:article_id => params[:id],:websiteid=>params[:websiteid]

  end


      def mytest3
      
      websid = Article.find(params[:id]).websitesinf_id
   redirect_to :controller=>'copyarticles',:action=>'mytest4',:id=>websid,:article_id => params[:id]

  end  

 

end
